<template>
  <div class="bannermodelbox">
    <el-dialog
      :showClose="false"
      :title="enterType === 1 ? 'Banner添加' : 'Banner修改'"
      :visible.sync="centerDialogVisible"
      height="40%"
      center
      width="30%"
    >
      <el-form label-width="100px" :model="bannerList">
        <el-form-item label="Banner名称">
          <el-input v-model="bannerList.bannerName"></el-input>
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model="bannerList.sort"></el-input>
        </el-form-item>
        <el-form-item label="Banner图片">
          <el-upload
            :class="{ uploadBox_hide: hideUploadEdit }"
            :key="uploadKey"
            :action="uploadURL"
            :file-list="fileList"
            list-type="picture-card"
            :show-file-list="true"
            :auto-upload="true"
            :on-success="picturesuccess"
            :before-upload="picturebefore"
            :on-error="pictureerror"
            :on-exceed="pictureexceed"
            :on-change="handleEditChange"
            :limit="1"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.imgUrl"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <!-- <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview2(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span> -->
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="跳转类型">
          <!-- {{ bannerList.bType }} -->
          <el-radio-group v-model="bannerList.bType" @input="radioType">
            <el-radio :label="1">商品</el-radio>
            <!-- <el-radio :label="2">活动</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品名称">
          <!-- {{ bannerList.bName }} -->
          <el-input style="width: 78%" v-model="bannerList.bName"></el-input>
          <el-button type="primary" @click="dialogTableVisible = true"
            >选择商品</el-button
          >
        </el-form-item>
        <el-form-item label="是否启用">
          <!-- {{ bannerList.isEnabled }} -->
          <!-- <el-input v-model="bannerList.isEnabled"></el-input> -->
          <el-radio-group v-model="bannerList.isEnabled" @input="radioEnabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelgoodesmodel">取 消</el-button>
        <el-button type="primary" @click="savegoodesmodel">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 选择商品 -->
    <el-dialog
      title="选择商品"
      height="40%"
      center
      width="30%"
      :visible.sync="dialogTableVisible"
    >
      <div style="margin-bottom: 20px">
        <el-input
          v-model="GoodsName"
          style="width: 300px; margin-right: 10px"
          placeholder="请输入商品名称"
          @change="GoodsNameHandle"
        ></el-input
        ><el-button
          @click="GoodsNameHandle"
          type="primary"
          icon="el-icon-search"
          >搜索</el-button
        >
      </div>

      <el-table
        v-loading="nameloading"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        :data="goodsList"
        border
      >
        <el-table-column property="mallName" label="店铺名称" width="232">
        </el-table-column>
        <el-table-column
          property="name"
          label="商品"
          width="232"
        ></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import { getGoods } from "@/api/mallApi/goodsOnsell/goodsOnsell";
import { AddBanner, editBanner } from "@/api/mallApi/managementend/mallset";
import { cloud } from "@/framework/utils/request";
export default {
  name: "BannerModel",
  components: {},
  props: {
    centerDialogVisible: Boolean,
    enterType: Number,
    currentRow: Object,
  },
  data() {
    return {
      nameloading: false,
      currentPage: 1,
      pageSize: 10,
      total: null,
      goodsList: [],
      GoodsName: "",
      dialogTableVisible: false,
      hideUploadEdit: false,
      uploadKey: 0,
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      uploadURL:
        process.env.VUE_APP_BASE_API +
        cloud.file +
        "/sysFileInfo/upload?secretFlag=N&fileBucket=mall",

      bannerList: {
        id: null,
        mallCode: null,
        modeCode: null,
        bannerName: "",
        bType: 1, //跳转类型（1：商品 2：活动）
        bValue: null, //活动或者商品id可选
        bannerPhoto: "",
        sort: 0,
        isEnabled: 1, //是否启用(0:禁用 1：启用)
        bName: "", //显示名称
      },
    };
  },
  methods: {
    radioEnabled(e) {},
    radioType(e) {},
    handleSizeChange(e) {
      //console.log("handleSizeChange");
    },
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getGoodsList();
      //console.log("handleCurrentChange", e);
    },
    GoodsNameHandle() {
      this.getGoodsList();
    },
    cancelgoodesmodel() {
      this.$emit("cancelgoodesmodel", false);
    }, // 取消按钮 传值
    savegoodesmodel() {
      if (this.enterType === 1) {
        AddBanner(this.bannerList).then((res) => {
          if (res.code === "00000") {
            this.$message({
              message: "Banner添加成功！",
              type: "success",
            });
            this.cancelgoodesmodel();
            this.$emit("refresh-banners");
          }
        });
      } else if (this.enterType === 2) {
        editBanner(this.bannerList).then((res) => {
          if (res.code === "00000") {
            this.$message({
              message: "Banner编辑成功！",
              type: "success",
            });
            this.cancelgoodesmodel();
            this.$emit("refresh-banners");
          }
        });
      }
    },
    //Banner图片上传
    // on-change添加文件，上传成功和上传失败时都会被调用
    handleEditChange(file, fileList) {
      //console.log("上传 和 成功都会调用 ？", file, fileList);
      this.hideUploadEdit = this.fileList.length >= fileList.length;
    },
    picturesuccess(response, file, fileList) {
      file.imgUrl = response.data.fileUrl;
      this.bannerList.bannerPhoto = response.data.fileUrl;
      // this.addgoodsinfo.imgList.push({
      //   goodsId: null,
      //   mallCode: null,
      //   type: "cover_photo",
      //   img: response.data.fileUrl,
      // });
      this.fileList.push({
        imgUrl: response.data.fileUrl,
      });
      //console.log(response);

      //console.log("fileList", fileList);
      //console.log("123---123", this.bannerList);
    },
    pictureerror(response, file, fileList) {},
    picturebefore(file) {
      //console.log(file.type);
      const isJPG = file.type === "image/jpeg" || "image/png" || "image/jpg" ;
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("Banner图只能是 JPEG,JPG,PNG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("Banner图大小不能超过10MB!");
      }
      this.uploadKey += 1;
      return isJPG && isLt10M;
    }, //图片大小格式校验
    pictureexceed(files, fileList) {
      if (fileList.length >= 4) {
        this.$message.error("图片最多上传1张!");
      }
    }, //图片限制提示
    handleRemove(file) {
      // 移除图片
      const index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
      this.hideUploadEdit = !(this.fileList.length === 0);
      //判断移除的 url是否存在 参数中，如果存在 则删除
      // const imgIndex = this.addgoodsinfo.imgList.findIndex(
      //   (img) => img.img === file.imgUrl
      // );

      // if (imgIndex !== -1) {
      //   this.addgoodsinfo.imgList.splice(imgIndex, 1);
      // }
    },
    clearImages() {
      // 清空图片列表
      this.fileList = [];
    },
    // handlePictureCardPreview(file) {
    //   this.dialogImageUrl = file.url;
    //   this.dialogVisible = true;
    // },
    getGoodsList() {
      this.nameloading = true;
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        isPage: 1,
        name: this.GoodsName,
        parentCategoryId: "",
        categoryId: "",
        ptStatus: 2,
        status: 2,
        isDelete: 0,
        type: "pt",
      };
      getGoods(params)
        .then((res) => {
          if (res.code === "00000") {
            //console.log("res", res);
            this.nameloading = false;
            this.goodsList = res.data.list;
            this.total = Number(res.data.total);
          }
        })
        .catch((error) => {});
    },
    handleEdit(e) {
      //console.log(e);
      this.bannerList.bName = e.name;
      this.bannerList.bValue = e.id;
      this.dialogTableVisible = false;
    },
  },
  mounted() {
    //console.log("currentRow", this.currentRow, "enterType", this.enterType);
    if (this.enterType === 2) {
      this.bannerList = this.currentRow;
      this.fileList.push({
        imgUrl: this.currentRow.bannerPhoto,
      });
      this.hideUploadEdit = this.fileList.length >= 1;
      //console.log("查看 2 的复制this.bannerList ", this.bannerList);
    }

    //console.log("model-mounted", this.currentRow);
    this.getGoodsList();
  },
  created() {},
  watch: {
    centerDialogVisible(newVal) {
      // 监听 centerDialogVisible 的变化
      if (!newVal) {
        // 当 centerDialogVisible 变为 false 时触发事件
        this.$emit("close-dialog");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./banner-models.scss";
</style>
